/**
 * Created by cchen on 2015/6/2.
 */

var toolUtil = require('../common/utils/toolUtil');
var mysqlUtil = require('../common/utils/mysqlUtil');
var async = require('async');
var Community = mongoose.model('community');
var Users = mongoose.model('user');
var moment = require('moment');
var inviteRecord = mongoose.model('invite_score_record');


exports.getLotteryDetailService = function (userId, lotteryId, callback) {
    var totalNum;
    async.series([
        function (callbackInner) {
            Users.findOne({_id: userId}).populate('community', 'communityName')
                .exec(function (err, result) {
                    var data = {
                        communityName: result.community.communityName,
                        isAuth: result.authenticationStatus
                    };
                    callbackInner(err, data)
                })
        },
        function (callbackInner) {
            var sql = 'SELECT * FROM lottery_activity WHERE id=?';
            mysqlUtil.query(sql, [lotteryId], function (err, result) {
                var data = {
                    name: result[0].activity_name,
                    desc: result[0].activity_desc,
                    startTime: result[0].begin_time,
                    endTime: result[0].end_time,
                    totalNum: result[0].lottery_limit
                };
                totalNum = result[0].lottery_limit;
                callbackInner(err, data);
            })
        },
        function (callbackInner) {
            var sql = 'SELECT COUNT(*) as count FROM lottery_log WHERE user_id=?';
            mysqlUtil.query(sql, [userId], function (err, result) {
                callbackInner(err, totalNum - result[0].count)
            })
        },
        function (callbackInner) {
            Users.findOne({_id: userId}, function (err, user) {
                var sql = 'SELECT * FROM lottery_prize p,lottery_award a WHERE p.lottery_id=? AND a.lottery_id=? AND a.prize_id=p.id and a.community_id=? AND p.prize_level=1';
                mysqlUtil.query(sql, [lotteryId, lotteryId, user.community + ''], function (err, result) {
                    if (result != null && result.length > 0) {
                        callbackInner(null, true);
                    } else {
                        callbackInner(null, false);
                    }
                });
            })
        },
        function (callbackInner) {
            var sql = 'SELECT * FROM lottery_award WHERE user_id=?';
            mysqlUtil.query(sql, [userId], function (err, result) {
                if (result != null && result.length > 0) {
                    callbackInner(null, true);
                } else {
                    callbackInner(null, false);
                }
            });
        }
    ], callback);
};

exports.generateLotteryTicketService = function (userId, lotteryId, callback) {
    var num = exports.getRandomNumber();
    var community;
    var name;

    var sql = 'SELECT COUNT(*) as count FROM lottery_log WHERE user_id=?';
    mysqlUtil.query(sql, [userId], function (err, result) {

        mysqlUtil.query('SELECT * from lottery_activity WHERE id=?', [lotteryId], function (err, activity) {

            if (activity[0].begin_time > new Date().getTime()) {
                callback({message: '活动尚未开始'})
            } else if (activity[0].end_time < new Date().getTime()) {
                callback({message: '活动已结束'})
            } else {

                name = activity[0].activity_name;
                if (activity[0].lottery_limit - result[0].count > 0) {
                    async.series([
                        function (callbackInner) {
                            Users.findOne({_id: userId}, function (err, result) {
                                community = result.community + '';
                                callbackInner(err, num);
                            })
                        },
                        function (callbackInner) {

                            if (num == '666') {
                                var sql = 'SELECT * FROM lottery_prize p,lottery_award a WHERE p.lottery_id=? AND a.lottery_id=? AND a.prize_id=p.id and a.community_id=? AND p.prize_level=1';
                                mysqlUtil.query(sql, [lotteryId, lotteryId, community], function (err, result) {
                                    var sql2;
                                    if (result != null && result.length > 0 && result.length >= result[0].prize_count) {
                                        sql2 = 'SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=2 AND p.product_id = d.id'
                                    } else {
                                        sql2 = 'SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=1 AND p.product_id = d.id'
                                    }
                                    mysqlUtil.query(sql2, [lotteryId], function (err, result) {
                                        if (result != null && result.length > 0) {

                                            var sql3 = 'SELECT COUNT(*) as count FROM lottery_award WHERE prize_id =? and community_id=?';

                                            mysqlUtil.query(sql3, [result[0].id, community], function (err, count) {
                                                if (result[0].prize_count != -1 && count[0].count >= result[0].prize_count) {
                                                    callbackInner({message: '无中奖次数'})
                                                } else {
                                                    var input = {
                                                        lottery_id: lotteryId,
                                                        user_id: userId,
                                                        prize_id: result[0].id,
                                                        community_id: community,
                                                        award_num: num,
                                                        create_time: new Date().getTime()
                                                    };
                                                    mysqlUtil.query('insert into lottery_award set?', input, function (err, data) {
                                                        callbackInner(err, result[0].name);
                                                        logger.info(result);
                                                        exports.giveUserAwardsService(userId, result[0].type, result[0].reward_count, name + result[0].level_name)
                                                    })
                                                }
                                            })
                                        } else {
                                            callbackInner({message: '无奖品信息'})
                                        }
                                    })
                                })
                            } else {
                                if (num != '000' && Number(num) % 6 == 0) {
                                    mysqlUtil.query('SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=3 AND p.product_id = d.id', [lotteryId], function (err, result) {
                                        if (result != null && result.length > 0) {
                                            logger.info(result);
                                            var sql3 = 'SELECT COUNT(*) as count FROM lottery_award WHERE prize_id =? and community_id=?';

                                            mysqlUtil.query(sql3, [result[0].id, community], function (err, count) {
                                                if (result[0].prize_count != -1 && count[0].count >= result[0].prize_count) {
                                                    callbackInner({message: '无中奖次数'})
                                                } else {
                                                    var input = {
                                                        lottery_id: lotteryId,
                                                        user_id: userId,
                                                        prize_id: result[0].id,
                                                        community_id: community,
                                                        award_num: num,
                                                        create_time: new Date().getTime()
                                                    };
                                                    mysqlUtil.query('insert into lottery_award set?', input, function (err, data) {
                                                        callbackInner(err, result[0].name);
                                                        exports.giveUserAwardsService(userId, result[0].type, result[0].reward_count, name + result[0].level_name)
                                                    });
                                                }
                                            });
                                        } else {
                                            callbackInner({message: '无奖品信息'})
                                        }
                                    })
                                } else {
                                    callbackInner();
                                }
                            }
                        },
                        function (callbackInner) {
                            var input = {
                                lottery_id: lotteryId,
                                user_id: userId,
                                award_num: num,
                                create_time: new Date().getTime()
                            };

                            if (num != '000' && Number(num) % 6 == 0) {
                                input.is_winning = 1
                            } else {
                                input.is_winning = 0
                            }
                            mysqlUtil.query('insert into lottery_log set?', input, callbackInner)
                        }
                    ], callback)
                } else {
                    var msg = {
                        message: '抽奖次数已经用完'
                    };
                    callback(msg, null)
                }
            }
        });
    });
};

exports.getRandomNumber = function () {
    var Num = '';
    for (var j = 0; j < 3; j++) {
        Num += Math.floor(Math.random() * 10);
    }
    return Num;
};


exports.getLotteryAwardListService = function (userId, lotteryId, page, callback) {

    var offset = (Number(page) - 1) * 10;
    Users.findOne({_id: userId}, function (err, result) {
        var community = result.community + '';

        var data = [];

        var sql = 'SELECT * from lottery_product d,lottery_prize p,lottery_award a WHERE a.prize_id = p.id and p.product_id = d.id and a.community_id=? and a.lottery_id=? ORDER BY prize_level,a.create_time DESC  limit ' + offset + ' ,10';
        mysqlUtil.query(sql, [community, lotteryId], function (err, result) {

            if (result != null) {
                logger.info(result);
                async.eachSeries(result, function (award, callbackInner) {
                    Users.findOne({_id: award.user_id}, 'nickName images roomUnit', function (err, user) {

                        var temp = {
                            nickName: user.nickName,
                            roomUnit: user.roomUnit,
                            images: user.images[0].imageURL.indexOf('http') == 0 ? user.images[0].imageURL : fastDfsHostIp + user.images[0].imageURL,
                            time: award.create_time,
                            awardNum: award.award_num,
                            prize: award.name
                        };
                        data.push(temp);
                        callbackInner();
                    })
                }, function (err) {
                    callback(err, data);
                })
            } else {
                callback(null, data);
            }
        })
    })
};


exports.giveUserAwardsService = function (userId, type, count, reason) {
    if (type == 2) {    //加情值奖励
        var input = {
            userId: userId + '',
            scoreAddCount: count,
            scoreAddRason: reason
        };

        input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

        scoreProxy.invoke('addScoreManual', [input], function (err, result) {
            if (err) {
                logger.error('Exception happened when addScoreManual ...!' + err.message);
            } else {
                var data = JSON.parse(decodeURIComponent(result));
                logger.info(data);
            }
        });
    }
};